package com.example.demo.controller;

import com.example.demo.model.Blog;
import com.example.demo.model.Register;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@RestController
public class UserController {
    @Resource
    public UserService userService;

    @RequestMapping("/login")
    public Object UserLogin(HttpServletRequest request,@RequestBody User user) {
        HashMap<String,Object> map = new HashMap<>();
        User user1 = userService.selectByName(user.getUsername());
        if(user1 == null) {
            map.put("message","不存在当前用户");
            return map;
        }
        if (!user1.getPassword().equals(user.getPassword())){
            map.put("message","当前用户名或密码错误");
            return map;
        }
        user.setUserId(user1.getUserId());

        HttpSession session = request.getSession(true);
        if (session != null) {
            session.setAttribute("user", user);
        }

        return map;
    }

    @RequestMapping("/register")
    public Object Register(@RequestBody Register register) {
        HashMap<String,Object> map = new HashMap<>();
        User user = userService.selectByName(register.username);
        if(user != null){
            map.put("message","当前用户名已经存在,请更换用户名!");
            return map;
        }
        User user1 = new User();
        user1.setUsername(register.username);
        user1.setPassword(register.password1);
        userService.addNewUser(user1);
        return map;
    }


}
